import { computed, ref } from 'vue'

export default function useShortcut (props, groupRef) {
  const scrollRef = ref(null)
  // 锚点高度
  const ANCHOR_HEIGHT = 20
  const touch = {}

  const shortcutList = computed(() => {
    return props.data.map((group) => group.title)
  })
  function onShortcutTouchStart (e) {
    const anchorIndex = parseInt(e.target.dataset.index)
    // 记录用户首次触摸时对应的索引值
    touch.anchorIndex = anchorIndex
    // 记录用户首次触摸时的垂直坐标
    touch.y1 = e.touches[0].pageY

    scrollTo(anchorIndex)
  }
  function onShortcutTouchMove (e) {
    touch.y2 = e.touches[0].pageY
    const delta = ((touch.y2 - touch.y1) / ANCHOR_HEIGHT) | 0
    const anchorIndex = touch.anchorIndex + delta
    scrollTo(anchorIndex)
  }
  function scrollTo (index) {
    // index范围：最小0，最大shortcutList数组最后一个索引
    index = Math.max(0, Math.min(shortcutList.value.length - 1, index))
    const targetEl = groupRef.value.children[index]
    const scrollInstance = scrollRef.value.scroll
    // scrollToElement(el,time,offsetX,offsetY)
    // el 滚动到的目标元素
    scrollInstance.scrollToElement(targetEl, 0)
  }
  return { shortcutList, scrollRef, onShortcutTouchStart, onShortcutTouchMove }
}
